package cc.customer.authorization.manager;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import cc.customer.authorization.Constants;
import cc.customer.authorization.util.MD5Utils;



/**
 * 通过Redis存储和验证token的工具类
 * @author Wang
 */
@Component
public class RedisTokenManager {

	@Resource
    private RedisTemplate<String, String> redisTemplate;
	
	/**
	 * 使用UUID作为token, 缓存到Redis并设置过期时间
	 */
    public String createToken(String userId) {
    	String token = UUID.randomUUID().toString().replaceAll("-", "");
    	redisTemplate.boundValueOps(Constants.REDIS_TOKEN_PREX + token).set(userId, Constants.TOKEN_EXPIRES_HOURS, TimeUnit.HOURS);
    	return token;
    }

    /**
     * 验证token是否存在，如果存在返回userId
     */
    public String checkToken(String token) {
    	if(token != null){
    		return redisTemplate.boundValueOps(Constants.REDIS_TOKEN_PREX + token).get();
    	}else{
    		return null;
    	}
    }
    
    /**
     * 设置token的过期时间
     */
    public void expireToken(String token) {
    	redisTemplate.boundValueOps(Constants.REDIS_TOKEN_PREX + token).expire(Constants.TOKEN_EXPIRES_HOURS, TimeUnit.HOURS);
    }
    
    /**
     * 删除token
     */
    public void deleteToken(String token) {
    	redisTemplate.delete(Constants.REDIS_TOKEN_PREX + token);
    }
    
    /**
     * 根据所有参数生成签名
     */
    public String createSign(Map<String, String> params) throws UnsupportedEncodingException {
        Set<String> keysSet = params.keySet();
        Object[] keys = keysSet.toArray();
        Arrays.sort(keys);
        StringBuffer sb = new StringBuffer();
        boolean first = true;
        for (Object key : keys) {
            if (first) {
                first = false;
            } else {
                sb.append("&");
            }
            sb.append(key).append("=");
            Object value = params.get(key);
            String valueString = "";
            if (null != value) {
                valueString = String.valueOf(value);
            }
            sb.append(URLEncoder.encode(valueString, "UTF-8"));
        }
        return MD5Utils.md5(sb.toString()).toUpperCase();
    }
    
    
}
